/**
 * 
 * @authors flyTeng (695508580@qq.com)
 * @date    2016-12-08 16:47:59
 * @version 1.0.0
 */
//inherit test
// function Test(argument) {
//     this.print = function(content) {
//         console.log(content);
//     }
// }

// function TestExtent() {
//     Test.call(this);
//     this.p = function() {
//         console.log(this);
//     }
// }

// var t = new TestExtent();
// t.p()



// function add(a, b){console.dir(this);}

// function sub(a, b){console.dir(this);}

// add(1,2);
// "Window"

// sub(1,2);
// "Window"

// add.call(sub, 1, 2);
// "sub(a, b)"
// add(1,2);

// sub.apply(add, [1, 2]);

//__PATH__ = "https://localhost/confession/back";

// __API__ = {
//     getMsg: __PATH__ + "/msgGet.php",
//     getCoverImg: __PATH__ + "/msgGetHeadUrl.php",
//     publishMsg: __PATH__ + "/msgPublish.php",
// }
__API__ = {
    getMsg: "/back/web/?r=wall/get",
    getCoverImg: "/back/web/?r=wall/getheadurl",
    publishMsg: "/back/web/?r=wall/publish",
}

var unburdenWall = angular.module('unburdenWall', ['ui.router']);

unburdenWall.directive('btmPublish', function() {
    return {
        scope: {
            publishdata: "=",
        },
        controller: function($scope, $element, $attrs, $transclude) {

        },
        restrict: 'AE',
        templateUrl: './tem/public/btmPublish.html',
        replace: true,
    };
});

unburdenWall.controller('dispatcher', function($scope, $http) {
    //data init
    sessionStorage.setItem("openid", GetQueryString("openid"));
    log(sessionStorage.getItem("openid"));
    get_msg();

    $scope.publishdata = {
        show: false,
        sex: 1,
        close: function() {
            $scope.publishdata.show = false;
        },
        publish: function() {
            log('SEX', $scope.publishdata.sex)
            var form = document.forms["msg_board"];
            form.onsubmit = function(e) {
                e.preventDefault();
                log("submit")
                var content = $$("board").value;
                if (trim(content).length == 0) {
                    alert("请问你想说的话呢？")
                } else {
                    log(content)
                    $http({
                        url: __API__.publishMsg,
                        method: "POST",
                        data: {
                            content: content,
                            sex: $scope.publishdata.sex,
                            openid: sessionStorage.getItem("openid")
                        },
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        transformRequest: function(obj){
                            var str = [];
                            for(var s in obj) {
                                str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                            }
                            return str.join("&");
                        }
                    }).success(function(data, status, headers, config) {
                        log(data)
                        if (data['error'] == 0) {
                            alert("发表成功 -。-")
                            refresh();
                        } else if (data['error'] == -1){
                            alert("珍惜每一次机会，一小时内只能发表一次 -。-")
                            refresh();
                        }
                    }).error(function(data, header, config, status) {
                        console.log(data);
                        console.log(header);
                        console.log(status);
                        alert('请检查网络连接')
                    });
                }
            }
        }
    }

    $scope.open_btm_bool = function() {
        $scope.publishdata.show = true;
    }

    $scope.person_icon = function(obj) {
        // log(obj)
        // var path = "./images/head_";
        // var radm = Math.floor(Math.random() * 16 + 1);
        // log(radm);
        // obj.src = path + radm + ".png";
        var path = "./images/";
        if (obj.sex == '1') {
            obj.src = path + "b.png";
        } else {
            obj.src = path + "g.png";
        }
    }

    get_img();

    function get_img() {
        $http({
            url: __API__.getCoverImg,
            method: "GET",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        }).success(function(data, status, headers, config) {
            log(data['url'])
            $$("appbar_img").src = data['url'];
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert('请检查网络连接')
        });
    }

    $scope.refresh = refresh;

    function refresh() {
        get_msg();
        $scope.publishdata.show = false;
        $scope.publishdata.sex = 1;
        pcont(1);
        document.body.scrollTop = 0;
    }

    window.onscroll = function(e) {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var scrollHeight = document.body.scrollHeight;
        var screenHeight = window.screen.height;
        var limit = (scrollTop + screenHeight) / scrollHeight
        if (limit >= 1) {
            var page = pcont();
            log(page);
            console.log(page);

            $http({
                url: __API__.getMsg,
                method: "POST",
                data: {
                    page: page,
                    openid: sessionStorage.getItem("openid")
                },
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj){
                    var str = [];
                    for(var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).success(function(data, status, headers, config) {
                log(data['error'])
                if (data['error'] == 0) {
                    $scope.msgs = $scope.msgs.concat(data['data']);             
                } else 
                    $scope.loading = false;
            }).error(function(data, header, config, status) {
                console.log(data);
                console.log(header);
                console.log(status);
                // alert('请检查网络连接')
            });
        }

    }

    function get_msg() {
        $http({
            url: __API__.getMsg,
            method: "POST",
            data: {
                openid: sessionStorage.getItem("openid")
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: function(obj){
                var str = [];
                for(var s in obj) {
                    str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                }
                return str.join("&");
            }
            // params: {},
        }).success(function(data, status, headers, config) {
            log(data['data'])
            if (data['data'].length < 5) {
                $scope.loading = false;
            }
            console.log(data['data'].length);
            $scope.msgs = data['data'];
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            // alert('请检查网络连接')
        });
    }

    var pcont = page_cont();

    function page_cont(reset) {
        var num = 1;
        return function(reset) {
            if (reset) {
                return num = 1;
            } else return num++;
        }
    }

    function GetQueryString(key) { //匹配参数
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var value = window.location.search.substr(1).match(reg);
        if (value != null)
            return unescape(value[2]);
        return null;
    }

    function trim(string) {
        return string.replace(/(^\s*)|(\s*$)/g, "");
    }

});

unburdenWall.config(router);

function router($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('', '/index').otherwise('/index');

    $stateProvider
        .state('index', {
            url: '/index',
            templateUrl: './index.html'
        });
}

function log(content) {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('[app]:');
    console.log.apply(console, args);
}

var $$ = function(id) {
    return document.getElementById(id);
};
